// Core
import axios from "axios";
import Cookies from "universal-cookie";
// Plg
import qs from "query-string";
// Util
import { SERVER_BASE, CODE_MESSAGE } from "@/config";
import { isInBrowser, redirectTo } from "./"
import { signOut } from "next-auth/react";

function getHeaders(req) {
  let token, cookies,X_CSRF_TOKEN;

  if (!isInBrowser()) {
    // 不在Client
    cookies = new Cookies(req.headers.cookie);
    token = cookies.get(`auth`);
  } else {
    // 在本地
    cookies = new Cookies(window.document.cookie);
    token = cookies.get(`auth`);
  }
  let headers = {};
  if (token) {
    headers['Authorization'] = `Bearer ${token}`
  }

  return headers;
}

/**
 * 检测状态
 * @param response
 * @returns {*}
 */
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response["data"];
  }
  const errortext = CODE_MESSAGE[response.status] || response.statusText;
  const error = new Error(errortext);
  error.statusCode = response.status;
  error.response = response;
  throw error;
}

export default function requewt(url, options) {
  const defaultOptions = {
    success: null,
    fail: null,
    cacheErr: null,
    req: null
  };
  const mergedOptions = {...defaultOptions, ...options};

  const {success, fail, req, cacheErr, body, method, headers: _headers} = mergedOptions;
  console.log(mergedOptions,'mergedoptions')
  const headers = Object.assign({}, _headers, getHeaders(mergedOptions));

  let reqOptions = {headers, method};

  if ([`POST`, `PUT`].includes(method)) {
    if (headers?.[`Content-Type`] === `multipart/form-data`) {
      let fm = new FormData();

      for (const bodyKey in body) {
        let value = body[bodyKey];
        if (Array.isArray(value)) {
          for (let i = 0; i < value.length; i++) {
            fm.append(`${bodyKey}[]`, value[i]);
          }
        } else {
          fm.append(bodyKey, value);
        }
      }
      reqOptions.data = fm;
    } else reqOptions.data = body;
  } else if (method === "DELETE") {
    if (body) reqOptions.data = body;
  }
  // GET
  else {
    if (body) url += `?${qs.stringify(body)}`;
  }
  const instance = axios.create({
    baseURL: process.NEXT_PUBLIC_API_PREFIX,
    headers
  });

  url = `${process.env.NEXT_PUBLIC_API_PREFIX}` + url;

  Object.assign(reqOptions, {url});

  return instance(reqOptions)
    .then(checkStatus)
    .then(data => {
      // console.log("data", data);
      if (data.status === 200) {
        if (success) success(data);
      } else {
        if (fail) fail(data);
      }
      return data;
    })
    .catch(e => {
      const STATUS = e?.response?.statusCode;
      // 如果是401 就直接登出
      // if ([403, 401].indexOf(STATUS)) {
      //   signOut()
      // }
      // console.log("Error in Requewt: ", e);
      if (cacheErr) cacheErr();
    });
}
